package com.nutransit;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.google.gson.Gson;
import com.mylibrary.mylibrary.imageloader.ImageLoader;
import com.mylibrary.mylibrary.parsing.AsyncTaskInterface;
import com.mylibrary.mylibrary.parsing.AsyncTaskUtility;
import com.mylibrary.mylibrary.util.CommonCode;
import com.mylibrary.mylibrary.util.SessionData;
import com.nutransit.commoncode.Webservice_parametrs;
import com.nutransit.service.MyService;

public class Fragment_Cab_Driver_List extends Fragment implements Webservice_parametrs
{
	private View rootview;
	private ListView lv_USER_REQUEST;
	private TextView tv_Request_Counter;
	
	private Context context;
	private ImageLoader imageLoader;
	private SessionData sessionData;
	
	private HashMap<String, String> hashMap;
	private String str_diverimgurl, str_vanrouteimgurl, strLatitude, strLongitude, strSource, strDestination,strprice,strdestination_lat,strDestinaltion_lon;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
	{
		rootview = inflater.inflate(R.layout.activity_user_request, container,false);
		init_var();
		
		get_data();
		return rootview;
	}

	private void init_var()
	{
		context = getActivity();
		imageLoader = new ImageLoader(context);
		sessionData = new SessionData(context, PACKAGE_NAME);
		
		tv_Request_Counter = (TextView) rootview.findViewById(R.id.tv_Request_Counter);
		rootview.findViewById(R.id.tv_USER_REQUEST).setVisibility(View.GONE);
		((ImageView)rootview.findViewById(R.id.iv_Logo)).setImageResource(R.drawable.ic_car);
		lv_USER_REQUEST = (ListView) rootview.findViewById(R.id.lv_USER_REQUEST);
		
		if(getArguments().containsKey(TAG_lat_source))
		{
			strLatitude = getArguments().getString(TAG_lat_source);
			strLongitude = getArguments().getString(TAG_long_source);
			strdestination_lat = getArguments().getString(TAG_lat_destination);
			strDestinaltion_lon = getArguments().getString(TAG_long_destination);
			strSource = getArguments().getString(TAG_source);
			strDestination = getArguments().getString(TAG_destination);
			strprice = getArguments().getString(TAG_price);
			System.out.println("Price pass :"+strprice);
		}
	}
	
	private void get_data()
	{
		hashMap = new HashMap<String, String>();
		hashMap.put(TAG_lat, strLatitude);
		hashMap.put(TAG_long, strLongitude);
		hashMap.put(TAG_flag, TAG_cab);
		
		new AsyncTaskUtility(context, hashMap, URL_GET_NU_VAN_DRIVERS).getJSONResponse(new AsyncTaskInterface()
		{
			@Override
			public void getJSONObjectFromAsynkTask(JSONObject json)
			{
				try
				{
					if(json!=null && json.getString(TAG_status).equalsIgnoreCase(SUCCESS))
					{
						str_vanrouteimgurl = json.getString("vanrouteimgurl");
						str_diverimgurl = json.getString("diverimgurl");
						JSONArray jsonArray_nucabdrivers = json.getJSONArray("nucabdrivers");
						if(jsonArray_nucabdrivers!=null)
						{
							tv_Request_Counter.setText(""+jsonArray_nucabdrivers.length());
							lv_USER_REQUEST.setAdapter(new 	Adapter_Cab_Driver_List(context, jsonArray_nucabdrivers));
						}
					}
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		});
	}
	
	public class Adapter_Cab_Driver_List extends BaseAdapter
	{
		private JSONArray jsonArray;
		private LayoutInflater inflater;

		public Adapter_Cab_Driver_List(Context context, JSONArray list)
		{
			this.jsonArray = list;
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount()
		{
			return jsonArray.length();
		}

		@Override
		public Object getItem(int position)
		{
			try
			{
				return jsonArray.get(position);
			}
			catch (JSONException e)
			{
				e.printStackTrace();
				return null;
			}
		}

		@Override
		public long getItemId(int position)
		{
			return position;
		}

		public class ViewHolder
		{
			TextView tv_Price, tv_UserName, tv_Address, tv_Accept;
			ImageView iv_Profile_Pic;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent)
		{
			try
			{
			final ViewHolder holder;

			if (convertView == null)
			{
				convertView = inflater.inflate(R.layout.list_row_user_request, parent, false);
				holder = new ViewHolder();
				holder.tv_Price = (TextView) convertView.findViewById(R.id.tv_Price);
				holder.tv_UserName = (TextView) convertView.findViewById(R.id.tv_UserName);
				holder.tv_Address = (TextView) convertView.findViewById(R.id.tv_Address);
				holder.tv_Accept = (TextView) convertView.findViewById(R.id.tv_Accept);
				holder.iv_Profile_Pic = (ImageView) convertView.findViewById(R.id.iv_Profile_Pic);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}

			holder.tv_Price.setVisibility(View.INVISIBLE);
			holder.tv_Address.setVisibility(View.VISIBLE);
			holder.iv_Profile_Pic.setVisibility(View.VISIBLE);
			
			
			final JSONObject jsonObject = jsonArray.getJSONObject(position);
			imageLoader.DisplayImage(str_diverimgurl+jsonObject.getString("photo"), holder.iv_Profile_Pic);	
			holder.tv_UserName.setText("$"+CommonCode.formatTo2Digit(""+strprice));
			holder.tv_Address.setText(""+jsonObject.getString("license_id"));
			holder.tv_Accept.setText(""+getString(R.string.RESERVE));
			
			holder.tv_Accept.setOnClickListener(new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					try
					{
						reserve_cab(jsonObject.getString(TAG_id));
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			});
		}
		catch (JSONException e)
		{
			e.printStackTrace();
			return null;
		}

			return convertView;
		}

		protected boolean reserve_cab(String strDriverId)
		{
			hashMap = new HashMap<String, String>();
			hashMap.put(TAG_van, "");
			hashMap.put(TAG_driverid, strDriverId);
			hashMap.put(TAG_userid, MainActivity_Nutransit.strUserId);
			hashMap.put(TAG_price, strprice);
			hashMap.put(TAG_startpoint, strSource);
			hashMap.put(TAG_endpoint, strDestination);
			hashMap.put(TAG_distance, "");
			
			new AsyncTaskUtility(context, hashMap, URL_RESERVE_NU_VAN_DRIVERS).getJSONResponse(new AsyncTaskInterface()
			{
				@Override
				public void getJSONObjectFromAsynkTask(JSONObject json)
				{
					try
					{
						if(json!=null && json.getString(TAG_status).equalsIgnoreCase(SUCCESS))
						{
							JSONObject jsonObject = json.getJSONArray(TAG_data).getJSONObject(0);
							String strReservationId = jsonObject.getString(TAG_idprimary);
							if(!MainActivity_Nutransit.arrayList_ReservationIds.contains(strReservationId))
								MainActivity_Nutransit.arrayList_ReservationIds.add(strReservationId);
							sessionData.setString(TAG_reservation_ids, new Gson().toJson(MainActivity_Nutransit.arrayList_ReservationIds));
							if(!CommonCode.isMyServiceRunning(MyService.class, context))
							{
								context.stopService(new Intent(context, MyService.class));
								context.startService(new Intent(context, MyService.class));
							}
							Bundle bundle = new Bundle();
							bundle.putString(TAG_data, jsonObject+"");
							bundle.putString(TAG_vanimageURL, str_vanrouteimgurl+"");
							bundle.putString(TAG_source, strSource+"");
							bundle.putString(TAG_destination, strDestination+"");
							bundle.putString(TAG_lat_source, strLatitude+"");
							bundle.putString(TAG_long_source, strLongitude+"");
							bundle.putString(TAG_lat_destination, strdestination_lat+"");
							bundle.putString(TAG_long_destination, strDestinaltion_lon+"");
							Fragment_Cab_Driver_Detail fragment_Cab_Driver_Detail = new Fragment_Cab_Driver_Detail();
							fragment_Cab_Driver_Detail.setArguments(bundle);
							final FragmentTransaction ft = getFragmentManager().beginTransaction();
							ft.add(R.id.fLayout_Container, fragment_Cab_Driver_Detail, "MyFragmentTag");
							ft.addToBackStack(null);
							ft.commit();
						}
					}
					catch (JSONException e)
					{
						e.printStackTrace();
					}
				}
			});
			return false;
		}
	}
}